const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const axios = require('axios');
const { TRANSITION_CONFIG, PATH_CONFIG } = require('../config/constants');
const { generateSafeFileName, cleanupFiles, ensureDirectoryExists } = require('../utils/fileUtils');
const { validateImageUrls, validateVideoConfig } = require('../utils/validation');
const { generateVideoTask } = require('../services/videoGenerator');
const QueueManager = require('../services/queueManager');

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, PATH_CONFIG.uploadDir);
    },
    filename: function (req, file, cb) {
        cb(null, generateSafeFileName(file.originalname));
    }
});

const upload = multer({ storage: storage });

// 下载图片函数
async function downloadImage(url, filepath) {
    try {
        console.log(`开始下载图片: ${url}`);
        console.log(`保存到: ${filepath}`);
        
        const response = await axios({
            url,
            method: 'GET',
            responseType: 'stream'
        });
        
        return new Promise((resolve, reject) => {
            const writer = fs.createWriteStream(filepath);
            response.data.pipe(writer);
            writer.on('finish', () => {
                console.log(`图片下载完成: ${filepath}`);
                resolve();
            });
            writer.on('error', (err) => {
                console.error(`图片下载失败: ${filepath}`, err);
                reject(err);
            });
        });
    } catch (error) {
        console.error('下载图片失败:', error.message);
        throw new Error(`下载图片失败: ${error.message}`);
    }
}

// 处理图片URL和视频生成
router.post('/generate-video-from-url', async (req, res) => {
    try {
        console.log('收到生成视频请求 - URL方式');
        console.log('请求参数:', JSON.stringify(req.body, null, 2));
        
        const { 
            imageUrls,
            transition = TRANSITION_CONFIG.defaultTransition,
            duration = TRANSITION_CONFIG.defaultDuration,
            offset = TRANSITION_CONFIG.defaultOffset,
            fps = TRANSITION_CONFIG.defaultFps,
            width = TRANSITION_CONFIG.defaultWidth,
            height = TRANSITION_CONFIG.defaultHeight,
            totalDuration = TRANSITION_CONFIG.defaultTotalDuration
        } = req.body;
        
        validateImageUrls(imageUrls);
        validateVideoConfig({ transition, duration, offset, fps, width, height, totalDuration });

        const jobId = `url_${Date.now()}_${Math.random().toString(36).substring(7)}`;
        const outputFileName = generateSafeFileName('output.mp4');
        const outputPath = path.join(PATH_CONFIG.outputDir, outputFileName);
        
        ensureDirectoryExists(PATH_CONFIG.outputDir);
        
        const imageFiles = [];
        
        // 下载所有图片
        for (let i = 0; i < imageUrls.length; i++) {
            const imageUrl = imageUrls[i];
            if (!imageUrl) {
                throw new Error(`第 ${i + 1} 个图片URL为空`);
            }

            const imageFileName = generateSafeFileName(imageUrl);
            const imagePath = path.join(PATH_CONFIG.uploadDir, imageFileName);
            
            await downloadImage(imageUrl, imagePath);
            imageFiles.push(imagePath);
        }

        // 将任务添加到队列
        const task = async () => {
            try {
                console.log('开始生成视频任务:', {
                    jobId,
                    imageCount: imageFiles.length,
                    outputPath,
                    config: { transition, duration, offset, fps, width, height, totalDuration }
                });

                const result = await generateVideoTask({
                    imageFiles,
                    outputPath,
                    transition,
                    duration,
                    offset,
                    fps,
                    width,
                    height,
                    totalDuration
                });
                
                console.log('视频生成成功:', {
                    jobId,
                    outputPath: result
                });
                
                // 清理下载的图片文件
                cleanupFiles(imageFiles);
                
                return result;
            } catch (error) {
                console.error('视频生成失败:', {
                    jobId,
                    error: error.message
                });
                // 发生错误时也要清理文件
                cleanupFiles(imageFiles);
                throw error;
            }
        };

        // 添加任务到队列并立即返回任务ID
        req.app.locals.queueManager.addJob(jobId, task);
        
        res.json({
            jobId,
            message: '视频生成任务已加入队列',
            status: 'pending'
        });

    } catch (error) {
        console.error('处理请求时出错:', error);
        res.status(500).json({ error: error.message || '服务器内部错误' });
    }
});

// 处理文件上传和视频生成
router.post('/generate-video', upload.array('images', 10), async (req, res) => {
    try {
        console.log('收到生成视频请求 - 文件上传方式');
        console.log('请求参数:', JSON.stringify(req.body, null, 2));
        console.log('上传文件信息:', JSON.stringify(req.files?.map(f => ({
            filename: f.filename,
            path: f.path,
            size: f.size
        })), null, 2));

        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ error: '请上传图片文件' });
        }

        const { 
            transition = TRANSITION_CONFIG.defaultTransition,
            duration = TRANSITION_CONFIG.defaultDuration,
            offset = TRANSITION_CONFIG.defaultOffset,
            fps = TRANSITION_CONFIG.defaultFps,
            width = TRANSITION_CONFIG.defaultWidth,
            height = TRANSITION_CONFIG.defaultHeight,
            totalDuration = TRANSITION_CONFIG.defaultTotalDuration
        } = req.body;

        validateVideoConfig({ transition, duration, offset, fps, width, height, totalDuration });

        const jobId = `upload_${Date.now()}_${Math.random().toString(36).substring(7)}`;
        const outputPath = path.join(PATH_CONFIG.outputDir, `output_${Date.now()}.mp4`);
        
        ensureDirectoryExists(PATH_CONFIG.outputDir);
        
        const imageFiles = req.files.map(file => file.path);

        // 将任务添加到队列
        const task = async () => {
            try {
                console.log('开始生成视频任务:', {
                    jobId,
                    imageCount: imageFiles.length,
                    outputPath,
                    config: { transition, duration, offset, fps, width, height, totalDuration }
                });

                const result = await generateVideoTask({
                    imageFiles,
                    outputPath,
                    transition,
                    duration,
                    offset,
                    fps,
                    width,
                    height,
                    totalDuration
                });
                
                console.log('视频生成成功:', {
                    jobId,
                    outputPath: result
                });
                
                // 清理上传的文件
                cleanupFiles(imageFiles);
                
                return result;
            } catch (error) {
                console.error('视频生成失败:', {
                    jobId,
                    error: error.message
                });
                // 发生错误时也要清理文件
                cleanupFiles(imageFiles);
                throw error;
            }
        };

        // 添加任务到队列并立即返回任务ID
        req.app.locals.queueManager.addJob(jobId, task);
        
        res.json({
            jobId,
            message: '视频生成任务已加入队列',
            status: 'pending'
        });

    } catch (error) {
        console.error('处理请求时出错:', error);
        res.status(500).json({ error: error.message || '服务器内部错误' });
    }
});

// 获取任务状态
router.get('/job-status/:jobId', (req, res) => {
    const { jobId } = req.params;
    const status = req.app.locals.queueManager.getJobStatus(jobId);
    
    if (!status) {
        return res.status(404).json({ error: '任务不存在' });
    }
    
    res.json(status);
});

// 获取队列状态
router.get('/queue-status', (req, res) => {
    res.json(req.app.locals.queueManager.getQueueStatus());
});

// 取消任务
router.post('/cancel-job/:jobId', (req, res) => {
    const { jobId } = req.params;
    const cancelled = req.app.locals.queueManager.cancelJob(jobId);
    
    if (!cancelled) {
        return res.status(404).json({ error: '任务不存在或无法取消' });
    }
    
    res.json({ message: '任务已取消' });
});

// 下载生成的视频
router.get('/download/:jobId', async (req, res) => {
    const { jobId } = req.params;
    const status = req.app.locals.queueManager.getJobStatus(jobId);
    
    if (!status || status.status !== 'completed') {
        return res.status(404).json({ error: '视频文件不存在或尚未生成完成' });
    }
    
    const outputPath = status.result;
    
    res.download(outputPath, (err) => {
        if (err) {
            console.error('下载文件时出错:', err);
        } else {
            console.log('视频文件已成功发送给客户端');
            // 延迟清理生成的视频文件
            setTimeout(() => {
                cleanupFiles([outputPath]);
            }, 1000);
        }
    });
});

module.exports = router; 